﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{

    public sealed class FPSSampler : MonoBehaviour
    {
        [SerializeField]
        [Tooltip("The statistics period time of sample.")]
        private float samplePeriod = 60.0f;

        [SerializeField]
        [Tooltip("The threshold for delta time avoid spike when the loading time.")]
        private float thresholdDeltaTime = 0.1f;

        private float sampleTimeLeft;
        private float sampleAccumTime;
        private int sampleFrameCount;

        public static event Action<int> FPSEvent;

        public float SamplePeriod
        {
            get { return this.samplePeriod; }
            set { this.samplePeriod = value; }
        }
        private void Awake()
        {
            this.sampleTimeLeft = this.samplePeriod;
            this.sampleAccumTime = 0.0f;
            this.sampleFrameCount = 0;
        }

        private void Update()
        {
            // Calculate sample FPS.
            var deltaTime = Mathf.Min(Time.unscaledDeltaTime, this.thresholdDeltaTime);
            this.sampleTimeLeft -= deltaTime;
            this.sampleAccumTime += deltaTime;
            ++this.sampleFrameCount;

            if (this.sampleTimeLeft <= 0.0f)
            {
                // Calculate the fps and notify this sample.
                if (FPSEvent != null)
                {
                    var fps = (int)(this.sampleFrameCount / this.sampleAccumTime);
                    FPSEvent(fps);
                }

                // Reset for the next period.
                this.sampleTimeLeft = this.samplePeriod;
                this.sampleAccumTime = 0.0f;
                this.sampleFrameCount = 0;
            }
        }

    }

}

